package com.news.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.news.bean.Link;
import com.news.dao.linkDao;
import com.news.dao.impl.LinkDaoImpl;
import com.news.util.DButil;
import com.news.util.NewsConfig;
import java.io.File;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Iterator;
import java.util.UUID;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class LinkServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Map map = new HashMap();
        Link L = new Link();
        linkDao ld = new LinkDaoImpl();
        String link = req.getParameter("link");
        //System.out.println("link"+"="+link);
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String address = req.getParameter("address");
        String img_logo = req.getParameter("img_logo");
        String sort = req.getParameter("sort");

        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        try {
            if (isMultipart) {

                    String path = this.getServletContext().getRealPath("/");
                    path += NewsConfig.logoFolder;
                    // Create a factory for disk-based file items
                    FileItemFactory factory = new DiskFileItemFactory();
                    // Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    upload.setHeaderEncoding("UTF-8");

                    // Parse the request
                    List items = upload.parseRequest(req); /* FileItem */
                    /* FileItem */
                    Iterator iter = items.iterator();
                    while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();
                        if (item.isFormField()) {
                            String UTF = item.getString("UTF-8");
                            map.put(item.getFieldName(), UTF);
                        } else {
                            String file = item.getName();
                            String type=null;
                            if (file.lastIndexOf(".") > 0) {
                                 type= file.substring(file.lastIndexOf("."));
                            }
                            String uuid=UUID.randomUUID().toString();
                            file=uuid+type;
                            path+=file;
                            File pic=new File(path);
                            if (!pic.getParentFile().exists()) {
                                pic.getParentFile().mkdirs();
                            }
                            item.write(pic);
                            map.put("img_logo", NewsConfig.logoFolder+file);
                        }
                    }


                link = (String) req.getParameter("link");
                id = (String) map.get("id");
                name = (String) map.get("name");
                address = (String) map.get("address");
                img_logo = (String) map.get("img_logo");
                sort = (String) map.get("sort");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (id != null) {
            L.setId(Integer.valueOf(id));
        }
        L.setName(name);
        L.setAddress(address);
        L.setImg_logo(img_logo);
        L.setSort(sort);
        if (link.equals("list")) {	//显示列表
            List<Link> list = ld.getlinkList(new HashMap());
            req.setAttribute("list", list);
            //resp.sendRedirect("link?link=list");
            req.getRequestDispatcher("link.jsp").forward(req, resp);
        }
        if (link.equals("add")) { //添加
            ld.addlink(L);
            //System.out.println(link.equals("addlink"));
            //System.out.println("ld.addlink();"+"="+ld.addlink());
            //req.getRequestDispatcher("link.jsp").forward(req, resp);
            resp.sendRedirect("link?link=list");
        }
        if (link.equals("edit")) { //修改
//            renameLogoPic(L.getId(), L.getImg_logo());
            ld.editlink(L);
            //System.out.println("id"+"=="+id);
            //System.out.println("ld.editlink()"+"="+ld.editlink(L));
            //req.getRequestDispatcher("link.jsp").forward(req, resp);
            resp.sendRedirect("link?link=list");
        }
        if (link.equals("delete")) { //删除
            //System.out.println(link.equals("delete"));
            ld.dellink(Integer.valueOf(id));
            //System.out.println("ld.dellink(Integer.valueOf(id))"+"="+ld.dellink(Integer.valueOf(id)));
            //req.getRequestDispatcher("link.jsp").forward(req, resp);
            resp.sendRedirect("link?link=list");
        }
    }

    public void renameLogoPic(int id, String newName) {
        try {
            Statement st = DButil.getStatement();
            String sql = "Select img_logo from link where id=" + id;
            boolean flag= st.execute(sql);
            ResultSet rs = st.getResultSet();
            rs.next();
            String oldFileName = rs.getString(1);
            String path = this.getServletContext().getRealPath("/");
            File oldFile=new File(path+NewsConfig.logoFolder+oldFileName);
            File newsFile=new File(path+NewsConfig.logoFolder+newName);
            oldFile.renameTo(newsFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }finally{
            DButil.close();
        }

    }

}
